package com.cloud.system.api.service.impl;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

import com.cloud.system.api.bean.*;
import com.cloud.system.api.entity.*;
import com.cloud.system.api.mapper.*;
import com.cloud.system.api.service.SysDictService;
import com.cloud.system.common.result.SelectItem;
import com.github.pagehelper.PageInfo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cloud.system.api.service.HumanInfoService;
import com.cloud.system.api.service.SystemCacheService;
import com.cloud.system.common.consts.SystemConst;
import com.cloud.system.common.result.QkTreeNode;
import com.cloud.system.common.utils.RedisKeyHelper;
import com.cloud.system.common.utils.SessionHelper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import tk.mybatis.mapper.entity.Example;

@Service
@Transactional
public class HumanInfoServiceImpl implements HumanInfoService {
    @Autowired
    private HumanInfoMapper humanInfoMapper;

    @Autowired
    private UnitInfoMapper unitInfoMapper;

    @Autowired
    private RoleInfoMapper roleInfoMapper;

    @Autowired
    private HumanRoleMapper humanRoleMapper;

    @Autowired
    private SystemCacheService systemCacheService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private UnitDomainMapper unitDomainMapper;

    @Autowired
    private SysDictService sysDictService;

    @Override
    public List<QkTreeNode> listHumanTree(long unitId, boolean isRoot, String isSupervise, boolean isScreen) {
        // 0918修改 组织机构树不再使用细分领域作为过滤条件，每个登录人就只能看到自己的所属单位及下级单位
        List<Integer> unitTypeIDs = new ArrayList<>();
        String humanType = "";
        if (StringUtils.isNotEmpty(isSupervise) && "true".equals(isSupervise)) {
            unitTypeIDs.add(5);
//            unitTypeIDs.add(0);
            humanType = "02";
        } else {
            unitTypeIDs.add(6);
            unitTypeIDs.add(2);
            unitTypeIDs.add(5);
            unitTypeIDs.add(4);
            humanType = "01";
        }

        //判断登录人的单位是否为行政区划，如果是行政区划的则不需要进行领域过滤，否则进行领域过滤
        UnitInfo SessionUnit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId());
        boolean isArea = "0".equals(SessionUnit.getUnitTypeId());

        List<QkTreeNode> nodes = new ArrayList<QkTreeNode>();
        QkTreeNode rootNode = null;
        UnitInfo rootUnit = null;
        if (isRoot) {
            if (unitId != 0) {
                rootUnit = unitInfoMapper.selectByPrimaryKey(unitId);
            } else {
                rootUnit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId());//
            }

            //根节点修改为所在部门的行政区划
            if (isArea) {
                rootUnit = getRegionInfo(rootUnit.getRegionCode(), isScreen);
            }
            rootNode = new QkTreeNode(rootUnit.getUnitId(), rootUnit.getUnitName());
            rootNode.setSelectable(true);
            if ("0".equals(rootUnit.getUnitTypeId())) {
                rootNode.setIcon("area");
            } else if ("4".equals(rootUnit.getUnitTypeId())) {
                rootNode.setIcon("entrust");
            } else if ("6".equals(rootUnit.getUnitTypeId())) {
                rootNode.setIcon("supervise");
            } else {
                rootNode.setIcon("unit");
            }
            rootNode.getData().put("code", rootUnit.getUnitCode());
            rootNode.getData().put("type", "U");
            rootNode.setExpanded(true);
        }
        if (null != rootNode) {
            nodes.add(rootNode);
        }

        // 加载机构下的人员
        List<QkTreeNode> humans = new ArrayList<QkTreeNode>();
        Example humanExample = new Example(HumanInfo.class);
        Example.Criteria humanCriteria = humanExample.createCriteria();
        if (StringUtils.isNotEmpty(isSupervise)) {
            if ("true".equals(isSupervise)) {
                humanCriteria.andEqualTo("humanType", "02");
            } else if ("false".equals(isSupervise)) {
                humanCriteria.andEqualTo("isLawHuman", "1");
                humanCriteria.andNotEqualTo("humanType", "00");
            }
        }

        //判断部门类型（行政区划下不加人员）
        if (!"0".equals(unitInfoMapper.selectByPrimaryKey(null != rootUnit ? rootUnit.getUnitId() : unitId).getUnitTypeId())) {
            humanCriteria.andNotEqualTo("deleteFlag", 1);
            humanCriteria.andEqualTo("unitId", null != rootUnit ? rootUnit.getUnitId() : unitId);
            humanExample.orderBy("displayOrder").asc();
            List<HumanInfo> humanInfos = humanInfoMapper.selectByExample(humanExample);
            if (null != humanInfos && humanInfos.size() > 0) {
                for (HumanInfo i : humanInfos) {
                    QkTreeNode node = new QkTreeNode(i.getHumanId(), i.getHumanName());
                    if (i.getGender() != null && i.getGender().equals(2)) {
                        node.setIcon("female-patrol");
                    } else {
                        node.setIcon("patrol");
                    }
                    node.setSelectable(true);
                    node.setLeaf(true);
                    node.getData().put("code", i.getUnitCode() + i.getHumanId() + "/");
                    node.getData().put("type", "H");
                    humans.add(node);
                }
            }
        }
        // 加载下级机构
        List<QkTreeNode> childrens = new ArrayList<QkTreeNode>();
        Example unitExample = new Example(UnitInfo.class);
        Example.Criteria unitCriteria = unitExample.createCriteria();
        if (StringUtils.isNotEmpty(isSupervise)) {
            if ("true".equals(isSupervise)) {
                List<Integer> unitTypeIds = new ArrayList<Integer>();
                // 展示行政区划和监督部门
                unitTypeIds.add(0);
                unitTypeIds.add(5);
                unitCriteria.andIn("unitTypeId", unitTypeIds);
            } else if ("false".equals(isSupervise)) {
                unitCriteria.andNotEqualTo("isLawOrgans", "0");
//                unitCriteria.andNotEqualTo("unitTypeId", "5");
            }
        }
        unitCriteria.andNotEqualTo("deleteFlag", 1);
        unitCriteria.andEqualTo("seniorId", null != rootUnit ? rootUnit.getUnitId() : unitId);
        unitExample.orderBy("displayOrder").asc();
        List<UnitInfo> units = unitInfoMapper.selectByExample(unitExample);

        // 判断下级机构是否为叶子节点
        if (null != units && units.size() > 0) {
            List<Long> uids = new ArrayList<>();
            uids.add(SessionUnit.getUnitId());
            List<Long> unitChildrenCounts;
            List<Long> unitRolesCounts;
            unitChildrenCounts = unitInfoMapper.selectUnitChildrenCount(uids, unitTypeIDs);
            unitRolesCounts = humanInfoMapper.selectUnitHumanCount(humanType, uids);
            for (UnitInfo u : units) {
                QkTreeNode node = new QkTreeNode(u.getUnitId(), u.getUnitName());
                if ("0".equals(u.getUnitTypeId())) {
                    node.setIcon("area");
                } else if ("4".equals(u.getUnitTypeId())) {
                    node.setIcon("entrust");
                } else if ("6".equals(u.getUnitTypeId())) {
                    node.setIcon("supervise");
                } else {
                    node.setIcon("unit");
                }
                node.setSelectable(true);
                node.getData().put("code", u.getUnitCode());
                node.getData().put("type", "U");
                node.setLeaf(true);
                //有子节点或者是登录人员所在部门的上层节点时设置为非叶子节点
                if (null != unitChildrenCounts && unitChildrenCounts.contains(u.getUnitId())) {
                    node.setLeaf(false);
                } else if ((SessionUnit.getUnitCode().indexOf(u.getUnitCode()) > -1 && !SessionUnit.getUnitId().equals(u.getUnitId())) || !checkLeafUnit(u, SessionUnit, unitTypeIDs, humanType)) {
                    node.setLeaf(false);
                }
                if (null != unitRolesCounts && unitRolesCounts.contains(u.getUnitId())) {
                    node.setLeaf(false);
                } else if ("0".equals(u.getUnitTypeId()) && containDirectUnit(u.getUnitId()) > 0) {
                    node.setLeaf(false);
                }
                if (isArea) {
                    childrens.add(node);
                } else if (!"0".equals(u.getUnitTypeId())) {
                    // 0909 修改 展示领域交集和父级单位下所有部门
                    if (SessionUnit.getUnitId().equals(u.getUnitId()) || u.getUnitCode().indexOf(SessionUnit.getUnitId().toString()) > -1) {
                        childrens.add(node);
                    }
                } else {
                    childrens.add(node);
                }
            }
        }
        if (nodes.size() != 1) {
            humans.addAll(childrens);
            return humans;
        } else {
            List<QkTreeNode> c = nodes.get(0).getChildren();
            c.addAll(childrens);
            c.addAll(humans);
        }
        return nodes;
    }

    public Integer containDirectUnit(Long unitID) {
        Example example = new Example(UnitInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("deleteFlag", 1);
        criteria.andEqualTo("seniorId", unitID);
        criteria.andEqualTo("unitTypeId", 0);
        criteria.andLike("unitName", "直属%");
        List<UnitInfo> units = unitInfoMapper.selectByExample(example);
        return units.size();
    }

    private Map<Long, List<String>> getAllSubDomains(long unitId) {

        Example example = new Example(UnitInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("deleteFlag", 1);
        criteria.andEqualTo("seniorId", unitId);
        example.orderBy("displayOrder").asc();
        List<UnitInfo> units = unitInfoMapper.selectByExample(example);

        List<Long> uids = new ArrayList<Long>();
        for (UnitInfo unit : units) {
            uids.add(unit.getUnitId());
        }

        Map<Long, List<String>> allSubDomainMap = new HashedMap();
        if (uids != null && uids.size() > 0) {
            example = new Example(UnitDomain.class);
            criteria = example.createCriteria();
            criteria.andIn("unitId", uids);
            List<UnitDomain> unitDomains = unitDomainMapper.selectByExample(example);

            List<String> list = new ArrayList<>();
            for (Long id : uids) {
                list = new ArrayList<>();
                for (UnitDomain domain : unitDomains) {
                    if (id.equals(domain.getUnitId())) {
                        list.add(domain.getSubDomainTypeId());
                    }
                }
                allSubDomainMap.put(id, list);
            }
        }

        return allSubDomainMap;
    }

    private List<String> getDomainStrings(long unitId) {
        Example example = new Example(UnitDomain.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("unitId", unitId);
        List<UnitDomain> unitDomains = unitDomainMapper.selectByExample(example);
        List<String> list = new ArrayList<>();
        for (UnitDomain domain : unitDomains) {
            list.add(domain.getDomainTypeId());
        }
        return list;
    }

    @Override
    public List<HumanInfo> search(String name) {
        Example hrExample = new Example(HumanInfo.class);
        Example.Criteria hrCriteria = hrExample.createCriteria();
        hrCriteria.andEqualTo("deleteFlag", 0);
        hrCriteria.andLike("humanName", "%" + name + "%");
        hrCriteria.andLike("unitCode", SessionHelper.get().getUnitCode() + "%");
        Page<HumanInfo> humanPage = PageHelper.startPage(1, 20).doSelectPage(() -> {
            humanInfoMapper.selectByExample(hrExample);
        });
        return humanPage.getResult();
    }

    @Override
    public List<HumanInfo> loadHumansByUnitId(long id, String isSupervise) {
        Example hrExample = new Example(HumanInfo.class);
        Example.Criteria hrCriteria = hrExample.createCriteria();
        hrCriteria.andEqualTo("deleteFlag", 0);
//        if (StringUtils.isNotEmpty(isSupervise) && "true".equals(isSupervise)) {
//            hrCriteria.andEqualTo("humanType", "02");
//        } else {
//            hrCriteria.andEqualTo("humanType", "01");
//        }
        hrCriteria.andEqualTo("unitId", id);
        hrCriteria.andEqualTo("isLawHuman", 1);
        hrCriteria.andNotEqualTo("humanType", "00");
        hrExample.orderBy("displayOrder");
        return humanInfoMapper.selectByExample(hrExample);
    }

    @Override
    public HumanInfo loadHuman(long id) {
        return humanInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<RoleInfo> loadRolesByHuman(long id) {
        return roleInfoMapper.selectHumanRoleByHuman(id);
    }

    @Override
    public HumanInfo load(long id) {
        HumanInfo humanInfo = humanInfoMapper.selectByPrimaryKey(id);

        //查询人员执法领域进行显示
        if (StringUtils.isEmpty(humanInfo.getDomain())) {
            List<String> list = getDomainStrings(humanInfo.getUnitId());
            StringBuffer buffer = new StringBuffer();
            List<SelectItem> selectItems = systemCacheService.loadSelectItem(SystemConst.UNIT_DOMAIN);
            if (list.size() > 0) {
                String[] array = new String[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    for (SelectItem selectItem : selectItems) {
                        if ((list.get(i)).equals(selectItem.getValue())) {
                            buffer.append(selectItem.getLabel());
                            buffer.append(", ");
                        }
                    }
                }
                String doMainValue = buffer.toString();
                if (StringUtils.isNotEmpty(doMainValue) && doMainValue.endsWith(", ")) {
                    doMainValue = doMainValue.substring(0, doMainValue.length() - 2);
                    humanInfo.setDomain(doMainValue);
                }
            }
        }
        return humanInfo;
    }

    @Override
    public HumanInfo showAdd(long unitId) {
        UnitInfo u = unitInfoMapper.selectByPrimaryKey(unitId);
        HumanInfo info = new HumanInfo();
        info.setUnitId(u.getUnitId());
        info.setUnitName(u.getUnitName());
        info.setUnitCode(u.getUnitCode());
        info.setLoginFlag(1);
        if (StringUtils.isEmpty(info.getDomain())) {
            List<String> list = getDomainStrings(info.getUnitId());
            StringBuffer buffer = new StringBuffer();
            List<SelectItem> selectItems = systemCacheService.loadSelectItem(SystemConst.UNIT_DOMAIN);
            if (list.size() > 0) {
                String[] array = new String[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    for (SelectItem selectItem : selectItems) {
                        if ((list.get(i)).equals(selectItem.getValue())) {
                            buffer.append(selectItem.getLabel());
                            buffer.append(", ");
                        }
                    }
                }
                String doMainValue = buffer.toString();
                if (StringUtils.isNotEmpty(doMainValue) && doMainValue.endsWith(", ")) {
                    doMainValue = doMainValue.substring(0, doMainValue.length() - 2);
                    info.setDomain(doMainValue);
                }
            }
        }
        return info;
    }


    @Override
    public Map<Integer,HumanInfo> saveUpdate(HumanInfo humanInfo) {
        Map<Integer,HumanInfo> map = new HashMap<>();
        Long humanId = humanInfo.getHumanId();
        humanInfo.setIsLawHuman(1);
        if (null != humanId && humanId != 0) {
            //修改人员信息后人员核实状态修改为0（未核实）
            humanInfo.setIsConfirm(0);
            humanInfo.setDeleteFlag(0);
            humanInfo.setLoginFlag(1);
            HumanInfo newHumanInfo = new HumanInfo();
            newHumanInfo = humanInfoMapper.selectByPrimaryKey(humanId);
            humanInfo.setHumanPassword(newHumanInfo.getHumanPassword());
            if (newHumanInfo.getNewAddFlag() != null) {
                humanInfo.setNewAddFlag(1);
            }
            if (newHumanInfo.getCreateHumanId() != null && newHumanInfo.getCreateHumanId() > 0) {
                humanInfo.setCreateHumanId(newHumanInfo.getCreateHumanId());
            }
            if (newHumanInfo.getCreateHuman() != null && newHumanInfo.getCreateHuman() != "") {
                humanInfo.setCreateHuman(newHumanInfo.getCreateHuman());
            }
            if (newHumanInfo.getCreateTime() != null) {
                humanInfo.setCreateTime(newHumanInfo.getCreateTime());
            }
            humanInfo.setUpdateTime(new Date());
            humanInfo.setSendStatus("U");
            humanInfo.setSendFlag(0);
            humanInfo.setUpdateHumanName(SessionHelper.get().getHumanName());
            humanInfo.setUpdateHumaneId(SessionHelper.get().getHumanId());
            humanInfoMapper.updateByPrimaryKey(humanInfo);
        } else {
            List<HumanInfo> humans = null;
            // 查询系统中是否有相同执法人员
            if (humanInfo.getLawCardNum() != null && !humanInfo.getLawCardNum().equals("")) {
                humans =humanInfoMapper.selectHumanByMameAndLawCard(humanInfo.getHumanName(), humanInfo.getLawCardNum(), humanInfo.getIdentityNum());
            }else {
                String sql = "select Human_id,unit_id,unit_name from human_info where identity_num = '" + humanInfo.getIdentityNum() + "' and delete_flag != 1;";
                humans = jdbcTemplate.query(sql, new BeanPropertyRowMapper<HumanInfo>(HumanInfo.class));
            }
            if (humans.size() > 0) {
                // 判断有多少重复人员
                if (humans.size() == 1) {
                    // 是否关联单位
                    if (humans.get(0).getUnitId() != null && humans.get(0).getUnitId() > 0) {
                        HumanInfo info = humanInfoMapper.selectByPrimaryKey(humans.get(0).getHumanId());
                        map.put(1,info);
                        return  map;
                    } else {
                        HumanInfoDetail info = humanInfoMapper.selectInfoById(humans.get(0).getHumanId());
                        BeanUtils.copyProperties(info,humanInfo);
                        humanInfo.setUpdateTime(new Date());
                        humanInfo.setDeleteFlag(0);
                        humanInfoMapper.updateByPrimaryKey(humanInfo);
                        map.put(2,humanInfo);
                        return map;
                    }
                } else {
                    map.put(3,humanInfo);
                    return map;
                }
            } else {
                humanInfo.setNewAddFlag(1);
                humanInfo.setSendFlag(0);
                humanInfo.setSendStatus("I");
                humanInfoMapper.insert(humanInfo);
                humanId = humanInfo.getHumanId();
                String defaultHumanPassword = systemCacheService.loadSysConfigItem(
                        SystemConst.DEFAULT_HUMAN_LOGIN_PASSWORD);
                if (StringUtils.isEmpty(defaultHumanPassword)) {
                    defaultHumanPassword = SystemConst.DEFAULT_HUMAN_LOGIN_PASSWORD;
                }
                humanInfo.setHumanPassword(
                        DigestUtils.md5Hex(defaultHumanPassword.concat(String.valueOf(humanId))).toUpperCase());
                humanInfo.setHumanId(humanId);
                String name = humanInfo.getHumanName();
                if (humanInfo.getBirthday() != null) {
                    SimpleDateFormat format = new SimpleDateFormat("MMdd");
                    name = humanInfo.getHumanName() + format.format(humanInfo.getBirthday());
                }
                int userNameCounts = humanInfoMapper.countByUserNameAndHumanId(name);
                if (userNameCounts > 0) {
                    humanInfo.setUserName(name + humanId);
                } else {
                    humanInfo.setUserName(name);
                }
                humanInfo.setDeleteFlag(0);
                humanInfo.setLoginFlag(1);
                humanInfo.setDisplayOrder(Integer.valueOf(humanId + ""));
                humanInfo.setCreateHumanId(SessionHelper.get().getHumanId());
                humanInfo.setCreateHuman(SessionHelper.get().getHumanName());
                humanInfo.setCreateTime(new Date());
                humanInfoMapper.updateByPrimaryKey(humanInfo);
                //保存人员岗位
                HumanRole hr = new HumanRole();
                String defaultHumanRoleId = systemCacheService.loadSysConfigItem(
                        SystemConst.DEFAULT_LAWYER_ROLE_ID_PRIFIX + humanInfo.getHumanType());
                if (StringUtils.isEmpty(defaultHumanRoleId)) {
                    defaultHumanRoleId = SystemConst.DEFAULT_LAWERY_ROLE_ID;
                }
                hr.setHumanId(humanId);
                hr.setRoleId(Long.valueOf(defaultHumanRoleId));
                humanRoleMapper.insert(hr);
                map.put(4,humanInfo);
                return map;
            }
        }
        map.put(0,humanInfo);
        return map;
    }

    @Override
    public long delete(long id) {
        HumanInfo humanInfo = humanInfoMapper.selectByPrimaryKey(id);
        humanInfo.setDeleteFlag(1);
        humanInfo.setSendStatus("D");
        humanInfoMapper.updateByPrimaryKey(humanInfo);
        return id;
    }

    @Override
    public long saveUpdateHumanRoles(HumanRoleForm form) {
        Example exp = new Example(HumanRole.class);
        Example.Criteria cri = exp.createCriteria();
        cri.andEqualTo("humanId", form.getHumanRoleId());
        humanRoleMapper.deleteByExample(exp);
        for (Long roleId : form.getIds()) {
            HumanRole hr = new HumanRole();
            hr.setRoleId(roleId);
            hr.setHumanId(form.getHumanRoleId());
            humanRoleMapper.insert(hr);
        }
        return form.getHumanRoleId();
    }

    @Override
    public List<HumanInfo> loadByUserName(String username) {
        Example example = new Example(HumanInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deleteFlag", 0);
        criteria.andEqualTo("userName", username);
        return humanInfoMapper.selectByExample(example);
    }

    @Override
    public int reorderHumans(final List<HumanInfo> humans) {
        jdbcTemplate.batchUpdate("update human_info set display_order = ? where human_id = ?",
                new BatchPreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement ps, int i) throws SQLException {
                        HumanInfo info = humans.get(i);
                        ps.setLong(1, info.getDisplayOrder());
                        ps.setLong(2, info.getHumanId());
                    }

                    @Override
                    public int getBatchSize() {
                        return humans.size();
                    }
                });
        return humans.size();
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, List<HumanImportBean>> analyseImportFile(List<HumanImportBean> humans) {
        List<HumanImportBean> success = new ArrayList<HumanImportBean>();
        List<HumanImportBean> error = new ArrayList<HumanImportBean>();

        Map<String, String> humanPositionLevel = MapUtils
                .invertMap(systemCacheService.listDictItemMap(SystemConst.HUMAN_POSITION_LEVEL));
        Map<String, String> humanPoliticalStatus = MapUtils
                .invertMap(systemCacheService.listDictItemMap(SystemConst.HUMAN_POLITICAL_STATUS));
        Map<String, String> humanEducation = MapUtils
                .invertMap(systemCacheService.listDictItemMap(SystemConst.HUMAN_EDUCATION));
        Map<String, String> humanNation = MapUtils
                .invertMap(systemCacheService.listDictItemMap(SystemConst.HUMAN_NATION));
        Map<String, String> humanNature = MapUtils
                .invertMap(systemCacheService.listDictItemMap(SystemConst.HUMAN_NATURE));
        Map<String, String> humanLawCardType = MapUtils
                .invertMap(systemCacheService.listDictItemMap(SystemConst.HUMAN_LAWCARD_TYPE));

        Map<String, String> yesNoDict = new HashMap<String, String>();
        yesNoDict.put("是", "1");
        yesNoDict.put("否", "0");

        for (HumanImportBean human : humans) {
            // 人员姓名
            if (StringUtils.isEmpty(human.getHumanName().trim())) {
                human.setError(true);
                human.getErrorMsg().add("姓名必填项");
            }
            // 身份证
            if (StringUtils.isEmpty(human.getIdentityNum())) {
                human.setError(true);
                human.getErrorMsg().add("证件号码为必填项目");
            } else {
                // TODO:校验身份证
            }
            // 职级
            if (!StringUtils.isEmpty(human.getPositionLevelName())) {
                String positionLevelCode = humanPositionLevel.get(human.getPositionLevelName());
                if (StringUtils.isEmpty(positionLevelCode)) {
                    human.setError(true);
                    human.getErrorMsg().add("职级填写错误");
                }
                human.setPositionLevel(positionLevelCode);
            }
            // 政治面貌
            if (!StringUtils.isEmpty(human.getPoliticalStatusName())) {
                String politicalStatusCode = humanPoliticalStatus.get(human.getPoliticalStatusName());
                if (StringUtils.isEmpty(politicalStatusCode)) {
                    human.setError(true);
                    human.getErrorMsg().add("政治面貌填写错误");
                }
                human.setPoliticalStatus(politicalStatusCode);
            }
            // 教育经历
            if (!StringUtils.isEmpty(human.getEducationName())) {
                String educationCode = humanEducation.get(human.getEducationName());
                if (StringUtils.isEmpty(educationCode)) {
                    human.setError(true);
                    human.getErrorMsg().add("最高学历填写错误");
                }
                human.setEducation(educationCode);
            }
            // 民族
            if (!StringUtils.isEmpty(human.getNationName())) {
                String getNationCode = humanNation.get(human.getNationName());
                if (StringUtils.isEmpty(getNationCode)) {
                    human.setError(true);
                    human.getErrorMsg().add("民族填写错误");
                }
                human.setNation(getNationCode);
            }
            // 人员属性
            if (!StringUtils.isEmpty(human.getHumanNatureName())) {
                String humanNatureCode = humanNature.get(human.getHumanNatureName());
                if (StringUtils.isEmpty(humanNatureCode)) {
                    human.setError(true);
                    human.getErrorMsg().add("人员属性填写错误");
                }
                human.setHumanNature(humanNatureCode);
            }
            // 执法证类别
            if (!StringUtils.isEmpty(human.getLawCardTypeName())) {
                String lawCardTypeCode = humanLawCardType.get(human.getLawCardTypeName());
                if (StringUtils.isEmpty(lawCardTypeCode)) {
                    human.setError(true);
                    human.getErrorMsg().add("执法证类别填写错误");
                }
                human.setLawCardType(lawCardTypeCode);
            }
            // 是否具有法律置業資格
            if (!StringUtils.isEmpty(human.getLawyerFlagName())) {
                String lawyerFlag = yesNoDict.get(human.getLawyerFlagName());
                if (StringUtils.isEmpty(lawyerFlag)) {
                    human.setError(true);
                    human.getErrorMsg().add("是否具公职律师填写错误");
                } else {
                    human.setLawcardFlag(Integer.valueOf(lawyerFlag));
                }

            }
            // 是否公职律师
            if (!StringUtils.isEmpty(human.getOccupFlagName())) {
                String occupFlag = yesNoDict.get(human.getOccupFlagName());
                if (StringUtils.isEmpty(occupFlag)) {
                    human.setError(true);
                    human.getErrorMsg().add("是否具有法律置资格格填写错误");
                } else {
                    human.setOccupFlag(Integer.valueOf(occupFlag));
                }

            }
            // 是否获得执法证
            if (!StringUtils.isEmpty(human.getLawcardFlagName())) {
                String lawcardFlag = yesNoDict.get(human.getLawcardFlagName());
                if (StringUtils.isEmpty(lawcardFlag)) {
                    human.setError(true);
                    human.getErrorMsg().add("是否获得执法证填写错误");
                } else {
                    human.setLawcardFlag(Integer.valueOf(lawcardFlag));
                }

            }
            if (human.isError()) {
                error.add(human);
            } else {
                success.add(human);
            }
        }
        Map<String, List<HumanImportBean>> result = new HashMap<String, List<HumanImportBean>>();
        result.put("success", success);
        result.put("error", error);
        return result;
    }

    @Override
    public Long importHumans(Long unitId, List<HumanInfo> humans) {
        UnitInfo parent = unitInfoMapper.selectByPrimaryKey(unitId);
        String defaultHumanPassword = systemCacheService.loadSysConfigItem(
                SystemConst.DEFAULT_HUMAN_LOGIN_PASSWORD);
        if (StringUtils.isEmpty(defaultHumanPassword)) {
            defaultHumanPassword = SystemConst.DEFAULT_HUMAN_LOGIN_PASSWORD;
        }
        for (HumanInfo info : humans) {
            long humanId = info.getHumanId();
            info.setHumanId(humanId);
            info.setUnitId(parent.getUnitId());
            info.setUnitName(parent.getUnitName());
            info.setUnitCode(parent.getUnitCode());
            info.setUserName(info.getIdentityNum());
            info.setHumanPassword(
                    DigestUtils.md5Hex(defaultHumanPassword.concat(String.valueOf(humanId))).toUpperCase());
            info.setDeleteFlag(0);
            humanInfoMapper.insert(info);
        }
        return null;
    }

    @Override
    public HumanProfile loadProfileInfo() {
        long humanId = SessionHelper.get().getHumanId();
        HumanInfo humanInfo = humanInfoMapper.selectByPrimaryKey(humanId);
        HumanProfile profile = new HumanProfile();
        BeanUtils.copyProperties(humanInfo, profile);
        return profile;
    }

    @Override
    public void updateProfile(HumanProfile profile) {
        HumanInfo humanInfo = humanInfoMapper.selectByPrimaryKey(profile.getHumanId());
        profile.setPassword(humanInfo.getHumanPassword());
        BeanUtils.copyProperties(profile, humanInfo);
        humanInfoMapper.updateByPrimaryKey(humanInfo);
    }

    @Override
    public boolean changePassword(HumanProfile profile){
        boolean issave = false;
        int flag = -1;
        //当密码为空时，能直接设置密码
        HumanInfo humanInfo = humanInfoMapper.selectByPrimaryKey(profile.getHumanId());
        if(humanInfo.getHumanPassword() == null || humanInfo.getHumanPassword() == ""){
            String code = DigestUtils.md5Hex(profile.getNewPassword().concat(String.valueOf(profile.getHumanId())));
            humanInfo.setHumanPassword(code.toUpperCase());
            flag = humanInfoMapper.updateByPrimaryKey(humanInfo);
            if(flag > 0){
                issave = true;
            }else {
                issave = false;
            }
            return issave;
        }
        String code = DigestUtils.md5Hex(profile.getPassword().concat(String.valueOf(profile.getHumanId())));
        if(humanInfo.getHumanPassword().equals(code.toUpperCase())){
            BeanUtils.copyProperties(profile, humanInfo);
            if (!StringUtils.isEmpty(profile.getNewPassword()) && profile.getNewPassword().equals(profile.getPasswordConfirm())) {
                code = DigestUtils.md5Hex(profile.getNewPassword().concat(String.valueOf(profile.getHumanId())));
                humanInfo.setHumanPassword(code.toUpperCase());
                flag = humanInfoMapper.updateByPrimaryKey(humanInfo);
            }
        }
        if(flag > 0){
            issave = true;
        }else {
            issave = false;
        }
        return issave;
    }

    @Override
    public HumanDetail loadHumanUnitDetail(long humanId) {
        HumanDetail detail = new HumanDetail();
        HumanInfo humanInfo = humanInfoMapper.selectByPrimaryKey(humanId);
        BeanUtils.copyProperties(humanInfo, detail);
        UnitInfo unitInfo = unitInfoMapper.selectByPrimaryKey(humanInfo.getUnitId());
        BeanUtils.copyProperties(unitInfo, detail);
        return detail;
    }

    @Override
    public PageInfo<HumanInfo> listPatrolPage(PatrolCriteriaBean criteria) {

        PageInfo<HumanInfo> page;
        UnitInfo unitInfo = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());
        criteria.setUnitCode(unitInfo.getUnitCode());

        page = PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize())
                .doSelectPageInfo(() -> {
                    humanInfoMapper.listPage(criteria);
                });
        Map humanNatureMap = MapUtils.invertMap(systemCacheService.listDictItemMap(SystemConst.HUMAN_NATURE));
        Map humanPositionLevelMap = MapUtils.invertMap(systemCacheService.listDictItemMap(SystemConst.HUMAN_POSITION_LEVEL));

        List<HumanInfo> list = page.getList();
        for (HumanInfo humanInfo : list) {
            humanInfo.setHumanNature(humanInfo.getHumanNature() == null ? "" : humanNatureMap.get(humanInfo.getHumanNature()).toString());
            humanInfo.setPositionLevel(humanInfo.getPositionLevel() == null ? "" : humanPositionLevelMap.get(humanInfo.getPositionLevel()).toString());
        }
        return page;
    }

    private String getDomainFilterString(UnitInfo unit) {
        String filter = "";
        if (!"0".equals(unit.getUnitTypeId())) {
            String unitDomains = getUnitDomains(unit.getUnitId());
            if (StringUtils.isNotEmpty(unitDomains)) {
                filter = " and unit_id in ( select unit_id from unit_domain where sub_domain_type_id in (" + unitDomains + ") ) ";
            }
        }
        return filter;
    }


    @Override
    public List<Map<String, Object>> getPatrolEduStat(Integer isSupervise) {

        String humanTypeFilter = " and human_type = '01'  ";
        if (isSupervise == 1) {
            humanTypeFilter = " and human_type = '02' ";
        }

        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());

        String filter = getDomainFilterString(unit);
        String regionFilter = getRegionFilterString(unit.getRegionCode());

        String sql = "SELECT dict_item_name,count from " +
                "(SELECT * from  sys_dict_item WHERE dict_key ='HUMAN_EDUCATION' ORDER BY display_order) a LEFT JOIN  " +
                "(SELECT education ,count(*) as count FROM human_info where delete_flag !=1 " + humanTypeFilter + filter + regionFilter + " GROUP BY education) b on a.dict_item_value = b.education ORDER BY display_order";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    private String getRegionFilterString(String regionCode) {
        UnitInfo unitInfo = getRegionInfo(regionCode,false);
        return " and unit_id in (select unit_id from unit_info where region_code like '" + unitInfo.getRegionCode() + "%') ";

    }

    @Override
    public List<Map<String, Object>> getPatrolNatureStat() {

        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());

        String filter = getDomainFilterString(unit);
        String regionFilter = getRegionFilterString(unit.getRegionCode());

        String sql = "SELECT dict_item_name,count from " +
                "(SELECT * from  sys_dict_item WHERE dict_key ='HUMAN_NATURE' ORDER BY display_order) a LEFT JOIN  " +
                "(SELECT human_nature ,count(*) as count FROM human_info where human_type = '01' and delete_flag !=1 " + filter + regionFilter + " GROUP BY human_nature) b on a.dict_item_value = b.human_nature ORDER BY display_order";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    public List<Map<String, Object>> getPatrolLawTypeStat(Integer isSupervise) {

        String humanTypeFilter = " and human_type = '01'  ";
        if (isSupervise == 1) {
            humanTypeFilter = " and human_type = '02' ";
        }

        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());

        String filter = getDomainFilterString(unit);
        String regionFilter = getRegionFilterString(unit.getRegionCode());

        String sql = "SELECT dict_item_name,count from " +
                "(SELECT * from  sys_dict_item WHERE dict_key ='UNIT_DOMAIN' ORDER BY display_order) a LEFT JOIN  " +
                "(SELECT domain_type_id ,count(*) as count from ( " +
                "SELECT human_id,domain_type_id from (SELECT * FROM human_info WHERE  human_type = '01' and delete_flag!=1 " + humanTypeFilter + filter + regionFilter + " ) a  LEFT JOIN unit_domain b ON a.unit_id = b.unit_id  ) t GROUP BY domain_type_id ) b on a.dict_item_value = b.domain_type_id ORDER BY count desc limit 10";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    public List<Map<String, Object>> getPatrolGenderStat(Integer isSupervise) {

        String humanTypeFilter = " and human_type = '01'  ";
        if (isSupervise == 1) {
            humanTypeFilter = " and human_type = '02' ";
        }

        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());

        String filter = getDomainFilterString(unit);
        String regionFilter = getRegionFilterString(unit.getRegionCode());

        String sql = "SELECT sum(case WHEN gender = '1' THEN count else 0 end) as man, " +
                "  sum(case WHEN gender = '2' THEN count else 0 end) as women FROM " +
                "(SELECT gender,count(*) as count from human_info  where delete_flag !=1 " + humanTypeFilter + filter + regionFilter + "  GROUP BY gender) t";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    public List<Map<String, Object>> getPatrolAreaStat(Integer isSupervise) {

        String humanTypeFilter = " and human_type = '01'  ";
        if (isSupervise == 1) {
            humanTypeFilter = " and human_type = '02' ";
        }

        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());
        int length = unit.getRegionCode().length();
        length = length + 2;
        String filter = getDomainFilterString(unit);
        String regionFilter = getRegionFilterString(unit.getRegionCode());

        String sql = "SELECT a.unit_name as dict_item_name,b.count from " +
                "(SELECT * from  unit_info WHERE LENGTH(region_code)=" + length + " and unit_type_id=0 and region_code like '" + unit.getRegionCode() + "%') a LEFT JOIN " +
                "(SELECT region_code ,count(*) as count from ( " +
                "SELECT human_id,LEFT(region_code," + length + ") as region_code from  (select * from human_info where  delete_flag !=1 " + humanTypeFilter + filter + regionFilter + ")  a  LEFT JOIN unit_info b ON a.unit_id = b.unit_id ) t GROUP BY region_code  " +
                ") b " +
                "on a.region_code = b.region_code";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    public List<Map<String, Object>> getPatrolCardStat() {

        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());

        String filter = getDomainFilterString(unit);
        String regionFilter = getRegionFilterString(unit.getRegionCode());

        String sql = "SELECT dict_item_name,count from " +
                "(SELECT * from  sys_dict_item WHERE dict_key ='HUMAN_LAWCARD_TYPE' ORDER BY display_order) a LEFT JOIN  " +
                "(SELECT law_card_type ,count(*) as count FROM human_info where  human_type = '01' and delete_flag !=1 " + filter + regionFilter + " GROUP BY law_card_type) b on a.dict_item_value = b.law_card_type ORDER BY display_order";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    public List<Map<String, Object>> getObtainLawCardStat() {
        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());

        String filter = getDomainFilterString(unit);
        String regionFilter = getRegionFilterString(unit.getRegionCode());

        String sql = "SELECT sum(case WHEN lawcard_flag = 1 THEN count else 0 end) as one, " +
                "  sum(case WHEN lawcard_flag = 0 THEN count else 0 end) as two FROM " +
                "(SELECT lawcard_flag,count(*) as count from human_info  where delete_flag !=1 and human_type = '02' " + filter + regionFilter + "  GROUP BY lawcard_flag) t";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    public List<Map<String, Object>> getLawyerStat() {
        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());

        String filter = getDomainFilterString(unit);
        String regionFilter = getRegionFilterString(unit.getRegionCode());

        String sql = "SELECT sum(case WHEN lawyer_flag = 1 THEN count else 0 end) as one, " +
                "  sum(case WHEN lawyer_flag = 0 THEN count else 0 end) as two FROM " +
                "(SELECT lawyer_flag,count(*) as count from human_info  where delete_flag !=1 and human_type = '02' " + filter + regionFilter + "  GROUP BY lawyer_flag) t";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    public List<Map<String,Object>> getLawCardFlagStat(){
        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());

        String filter = getDomainFilterString(unit);
        String regionFilter = getRegionFilterString(unit.getRegionCode());

        String sql = "SELECT sum(case WHEN lawcard_flag = 1 THEN count else 0 end) as one, " +
                "  sum(case WHEN lawcard_flag = 0 THEN count else 0 end) as two FROM " +
                "(SELECT lawcard_flag,count(*) as count from human_info  where delete_flag !=1 and human_type = '01' " + filter + regionFilter + "  GROUP BY lawcard_flag) t";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }


    private UnitInfo getRegionInfo(String regionCode,boolean isScreen) {
        Example example = new Example(UnitInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("regionCode", regionCode);
        criteria.andEqualTo("unitTypeId", 0);
        UnitInfo unitInfo = unitInfoMapper.selectByExample(example).get(0);
        //直属部门 ，就再找一级
        if(unitInfo.getUnitName().indexOf("直属")>-1 && !isScreen){
            example = new Example(UnitInfo.class);
            criteria = example.createCriteria();
            criteria.andEqualTo("unitId", unitInfo.getSeniorId());
            criteria.andEqualTo("unitTypeId", 0);
            unitInfo = unitInfoMapper.selectByExample(example).get(0);
        }
        return unitInfo;
    }

    private boolean checkSeniorUnit(Long unitID) {
        boolean isArea = false;
        Example example = new Example(UnitInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("unitId", unitID);
        List<UnitInfo> unitInfos = unitInfoMapper.selectByExample(example);
        if(unitInfos!=null && unitInfos.size()>0){
            if ("0".equals(unitInfos.get(0).getUnitTypeId())) {
                isArea = true;
            } else {
                isArea = false;
            }
        }

        return isArea;
    }


    private boolean checkLeafUnit(UnitInfo node,UnitInfo sessionUnit, List<Integer> unitTypeIds,String humanType) {
        boolean isLeaf = true;
        if(node.getUnitCode().contains(sessionUnit.getUnitId().toString())){
            List<Long> list = new ArrayList<>();
            list.add(node.getUnitId());
            List<Long> humanCount = humanInfoMapper.selectUnitHumanCount(humanType, list);
            List<Long> longs = unitInfoMapper.selectUnitChildrenCount(list, unitTypeIds);
            if(longs.contains(node.getUnitId()) || humanCount.contains(node.getUnitId())){
                isLeaf = false;
            }
        }
        return isLeaf;
    }

    private String getUnitDomains(Long unitID) {
        List<SelectItem> selectItems = systemCacheService.loadUnitDomains(unitID);
        List<String> list = new ArrayList<>();
        for (SelectItem selectItem : selectItems) {
            list.add(selectItem.getValue().toString());
        }
        return StringUtils.join(list, ",");
    }
    @Override
    public List<HumanDetail> searchLawyers(long unitId, String query) {
        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(unitId);
        List<HumanDetail> humans = null;
        if (null != unit.getSubjectId() && unit.getSubjectId() > 0) {
            //加载执法主体下的人员信息
            humans = jdbcTemplate.query("select human_id,human_name,law_card_num from human_info where unit_id in (select unit_id from unit_info where (unit_id = ? or senior_id = ?) and delete_flag != 1) and " +
                    "human_name like ? and human_type != '00' and delete_flag != 1",new BeanPropertyRowMapper<HumanDetail>(HumanDetail.class),unit.getSubjectId(),unit.getSubjectId(),"%" + query + "%");
        }

        return humans;
    }

    @Override
    public Map<String, Object> getPatrolAreaStatForScreen(Integer isSupervise, Long regionid) {

        String humanTypeFilter = " and is_law_human = '1' AND  human_type != '00'";
        if (isSupervise == 1) {
            humanTypeFilter = " and is_law_human = '0' AND  human_type != '00'";
        }

        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());
        String humanFilter = "AND LENGTH(region_code)=4";
        String reFilter = "LEFT (region_code, 4) AS region_code";
        if (regionid != null && regionid != 1) {
            humanFilter = "AND senior_id = '" + regionid + "'";
            reFilter = "region_code";
            unit = unitInfoMapper.selectByPrimaryKey(regionid);
        }

        UnitInfo unitInfo = getRegionInfo(unit.getRegionCode(),false);
        String filter = getDomainFilterString(unit);
        String regionFilter = getRegionFilterString(unit.getRegionCode());

        String sql = "SELECT   a.unit_id AS regionid, a.unit_name AS regionname,  a.region_code AS regioncode,a.senior_id AS seniorid,   b.count AS sumnum from " +
                "(SELECT * from  unit_info WHERE  unit_type_id=0 " + humanFilter + ") a LEFT JOIN  (SELECT region_code ,count(*) as count from (  SELECT human_id," + reFilter + " from  (select * from human_info where  delete_flag !=1 " + humanTypeFilter + filter + regionFilter + ")  a  LEFT JOIN unit_info b ON a.unit_id = b.unit_id ) t GROUP BY region_code  ) b  on a.region_code = b.region_code";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        List<SysDictItem> itemList = sysDictService.loadDictByDictItemValue(unitInfo.getUnitTypeId(), "UNIT_TYPE");

        Map<String, Object> returnList = new HashedMap();
        Map<String, Object> statMap = new HashedMap();
        Map<String, Object> regionMap = new HashedMap();
        list.forEach(v -> {
            List<Map<String, Object>> typeList = new ArrayList<>();
            Map<String, Object> typeMap = new HashedMap();
            v.putIfAbsent("sumnum", "0");
            v.put("regioncode", regionIdFormat(v.get("regioncode").toString()));
            itemList.forEach(j -> {
                typeMap.put("code", j.getDictItemValue());
                typeMap.put("name", j.getDictItemName());
                typeMap.put("num", v.get("sumnum"));
            });
            typeList.add(typeMap);
            v.put("types", typeList);
        });
        regionMap.put("regionid", unitInfo.getUnitId());
        regionMap.put("regioncode", regionIdFormat(unitInfo.getRegionCode()));
        regionMap.put("regionname", unitInfo.getUnitName());
        final int[] i = {0};
        list.stream().forEach(sun -> {
            i[0] += Integer.parseInt(sun.get("sumnum").toString());
        });
        regionMap.put("sumnum", i[0]);
        regionMap.put("seniorid", unitInfo.getSeniorId());
        statMap.put("children", list);
        statMap.put("region", regionMap);
        returnList.put("stat", statMap);
        return returnList;
    }

    @Override
    public List<Map<String, Object>> getPatrolAgeStat() {
        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());

        String filter = getDomainFilterString(unit);
        String regionFilter = getRegionFilterString(unit.getRegionCode());

        String sql = "SELECT  sum(case WHEN ( age>20 and age<=30) THEN 1 ELSE 0 end)  as ageOne, " +
                "sum(case WHEN ( age>30 and age<=40) THEN 1 ELSE 0 end) as ageTwo, " +
                "sum(case WHEN ( age>40 and age<=50) THEN 1 ELSE 0 end)  as ageThree, " +
                "sum(case WHEN ( age>50 and age<=60) THEN 1 ELSE 0 end)  as ageFour, " +
                "sum(case WHEN ( age>60) THEN 1 ELSE 0  end)  as ageFive from " +
                "(SELECT human_id,TIMESTAMPDIFF(year,birthday,NOW()) as age from human_info WHERE human_type='01' and  delete_flag=0 " + filter + regionFilter + ") t WHERE age is not null ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    public long confirm(long id) {
        HumanInfo humanInfo = humanInfoMapper.selectByPrimaryKey(id);
        humanInfo.setIsConfirm(1);
        humanInfoMapper.updateByPrimaryKey(humanInfo);
        return id;
    }

    @Override
    public Integer getPatrolCount(Integer isSupervise) {
        String humanTypeFilter = " and human_type = '01'  ";
        if (isSupervise == 1) {
            humanTypeFilter = " and human_type = '02' ";
        }

        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());
        String filter = getDomainFilterString(unit);
        String regionFilter = getRegionFilterString(unit.getRegionCode());


        String sql = "select count(*) from human_info where delete_flag = 0  " + humanTypeFilter + filter + regionFilter;
        Integer humanCount = jdbcTemplate.queryForObject(sql, Integer.class);
        return humanCount;
    }

    private String regionIdFormat(String regionId) {
        int n = 6;
        if (StringUtils.isNotBlank(regionId) && regionId.length()<n){
            return regionId+String.format("%1$0"+(n-regionId.length())+"d",0);
        }
        return regionId;
    }

    @Override
    public void humanUnitAdjust(HumanUnitAdjustBean adjustBean) {
        jdbcTemplate
                .update("update human_info t1, unit_info t2 set t1.unit_id = t2.unit_id, t1.unit_name = t2.unit_name, t1.unit_code = t2.unit_code where t2.unit_id = ? and t1.human_id in ("
                        + StringUtils.join(adjustBean.getIds(), ",") + ")", adjustBean.getUnitId());
    }

    @Override
    public Map<String, List<HumanInfo>> searchAddStaff(String params){
        List<String> searchConditions = new ArrayList<>();
        List<HumanInfo> humanList = new ArrayList<>();
        Map humanMap = new HashMap<String, List<HumanInfo>>();
        String sql = "";
        String[] searchParams = params.split("；");
        for (int i = 0; i < searchParams.length; i++) {
            if(searchParams[i].length() == 18 && Pattern.matches("^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$", searchParams[i])){
                searchConditions.add("identity_num = '" + searchParams[i] + "'");
            }else if(searchParams[i].length() == 15 && Pattern.matches("^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$", searchParams[i])){
                searchConditions.add("identity_num = '" + searchParams[i] + "'");
            }else if(searchParams[i].matches(".*\\d.*")){
                searchConditions.add("law_card_num = '" + searchParams[i] + "'");
            }else {
                searchConditions.add("human_name = '"  + searchParams[i] + "'");
            }
        }
        String searchCondition = String.join(" or ",searchConditions);
        sql = "select human_id,human_name,law_card_num,identity_num,unit_id,unit_name from human_info where human_id in " +
                "(select human_id from human_info  where " + searchCondition + ") and delete_flag != 1 and human_type != '00'";
        List<HumanInfo> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<HumanInfo>(HumanInfo.class));
        if (list.size() == 0) {
            humanMap.put("false", null);
        }  else {
            for (HumanInfo human: list) {
                humanList.add(human);
            }
            humanMap.put("true", humanList);
        }

        return humanMap;
    }

    @Override
    public List<HumanInfo> loadStaffsByUnitId(Long unitId,String humanType){
        return humanInfoMapper.loadStaffsByUnitId(unitId,humanType);
    }

    @Override
    public void addStaff(HumanInfo huamnInfo){
        HumanInfo human = humanInfoMapper.selectByPrimaryKey(huamnInfo.getHumanId());
        human.setUnitId(huamnInfo.getUnitId());
        human.setUnitName(huamnInfo.getUnitName());
        human.setUnitCode(huamnInfo.getUnitCode());
        human.setHumanType(huamnInfo.getHumanType());
        human.setUpdateTime(new Date());
        humanInfoMapper.updateByPrimaryKey(human);
    }

    @Override
    public void delStaff(Long humanId){
        HumanInfo humanInfo = humanInfoMapper.selectByPrimaryKey(humanId);
        humanInfo.setUnitId(null);
        humanInfo.setUnitName(null);
        humanInfo.setUnitCode(null);
        humanInfo.setUpdateTime(new Date());
        humanInfoMapper.updateByPrimaryKey(humanInfo);
    }
	@Override
	public List<WfActPart> transSearch(String partType, long partId, long unitId, boolean filter) {
		StringBuilder sqlBuilder = null;
		if("R".equals(partType)){
			sqlBuilder = new StringBuilder("SELECT h.human_id AS partId, h.human_name AS partName, 'H' AS partType FROM human_info h, human_role hr WHERE hr.human_id = h.human_id AND hr.role_id = ?");
			if(filter){
				sqlBuilder.append(" AND h.unit_id = ").append(unitId);
			}
			sqlBuilder.append(" limit 100 ");
		}else if("U".equals(partType)){
			sqlBuilder = new StringBuilder("SELECT h.human_id AS partId, h.human_name AS partName, 'H' AS partType FROM human_info h WHERE h.unit_id = ? LIMIT 100");
		}
		return jdbcTemplate.query(sqlBuilder.toString(), new BeanPropertyRowMapper<WfActPart>(WfActPart.class), partId);
	}

	@Override
	public int resetPassword(Long humanId) {
        HumanInfo humanInfo = humanInfoMapper.selectByPrimaryKey(humanId);
        String defaultHumanPassword = systemCacheService.loadSysConfigItem(
                SystemConst.DEFAULT_HUMAN_LOGIN_PASSWORD);
        if (StringUtils.isEmpty(defaultHumanPassword)) {
            defaultHumanPassword = SystemConst.DEFAULT_HUMAN_LOGIN_PASSWORD;
        }
        humanInfo.setHumanPassword(
                DigestUtils.md5Hex(defaultHumanPassword.concat(String.valueOf(humanId))).toUpperCase());
        return humanInfoMapper.updateByPrimaryKey(humanInfo);
    }

    @Override
    public HumanDetail getHumanInfoByUnitId(Long unitId) {
        HumanDetail humanDetail = humanInfoMapper.getUnitAdministratorByUnitId(unitId);
        HumanInfo humanInfo = humanInfoMapper.selectByPrimaryKey(humanDetail.getHumanId());
        BeanUtils.copyProperties(humanInfo, humanDetail);
        UnitInfo unitInfo = unitInfoMapper.selectByPrimaryKey(humanInfo.getUnitId());
        BeanUtils.copyProperties(unitInfo, humanDetail);
        return humanDetail;
    }
}
